package com.tencent.wxcloudrun;

import com.alibaba.fastjson.JSON;
import com.tencent.wxcloudrun.dto.WechatMsgDTO;
import com.tencent.wxcloudrun.model.e.MsgType;
import org.springframework.stereotype.Service;

/**
 * @author zhe.wang@weimob.com
 * @date 2023/4/3 下午6:02
 */
@Service
public class WechatMsgRespManager {

    public WechatMsgDTO response(WechatMsgDTO msgDTO) {
        if (MsgType.TEXT.getCode().equals(msgDTO.getMsgType())) {
            return respText(msgDTO);
        } else if (MsgType.IMAGE.getCode().equals(msgDTO.getMsgType())) {
            return respImage(msgDTO);
        }else if (MsgType.EVENT.getCode().equals(msgDTO.getMsgType())) {
            return respEvent(msgDTO);
        }
        return null;
    }


    private WechatMsgDTO respText(WechatMsgDTO msgDTO) {

        WechatMsgDTO respMsg = new WechatMsgDTO();
        respMsg.setToUserName(msgDTO.getFromUserName());
        respMsg.setFromUserName(msgDTO.getToUserName());
        respMsg.setMsgType(MsgType.TEXT.getCode());
        respMsg.setContent("我知道了");
        respMsg.setCreateTime(System.currentTimeMillis());

        return respMsg;
    }

    private WechatMsgDTO respImage(WechatMsgDTO msgDTO) {
        WechatMsgDTO respMsg = new WechatMsgDTO();
        respMsg.setToUserName(msgDTO.getFromUserName());
        respMsg.setFromUserName(msgDTO.getToUserName());
        respMsg.setMsgType(MsgType.TEXT.getCode());
        respMsg.setContent("别给我发图片了，不支持");
        respMsg.setCreateTime(System.currentTimeMillis());
        return respMsg;
    }

    private WechatMsgDTO respEvent(WechatMsgDTO msgDTO) {
        WechatMsgDTO respMsg = new WechatMsgDTO();
        respMsg.setToUserName(msgDTO.getFromUserName());
        respMsg.setFromUserName(msgDTO.getToUserName());
        respMsg.setMsgType(MsgType.TEXT.getCode());
        respMsg.setContent("哇塞 你来了！");
        respMsg.setCreateTime(System.currentTimeMillis());
        return respMsg;
    }


    public String toXml(WechatMsgDTO wechatMsgDTO) {
        String s = "<xml>  " +
                "   <ToUserName><![CDATA[" + wechatMsgDTO.getToUserName() + "]]></ToUserName>  " +
                "   <FromUserName><![CDATA[" + wechatMsgDTO.getFromUserName() + "]]></FromUserName>  " +
                "   <CreateTime>" + wechatMsgDTO.getCreateTime() + "</CreateTime>  " +
                "   <MsgType><![CDATA[" + wechatMsgDTO.getMsgType() + "]]></MsgType>  " +
                "   <Content><![CDATA[" + wechatMsgDTO.getContent() + "]]></Content>" +
                "</xml>";

        return s;
    }

    public String toJSON(WechatMsgDTO wechatMsgDTO){
        return JSON.toJSONString(wechatMsgDTO);
    }
}
